<?php
// no direct acceso
defined( '_JEXEC' ) or die( 'Restricted access' );

// Import library dependencies
#jimport('joomla.event.plugin');
#jimport('joomla.event.helper');

class mgmediabot2 extends JPlugin
{
   /**
    * Constructor
    *
    * For php4 compatability we must not use the __constructor as a constructor for
    * plugins because func_get_args ( void ) returns a copy of all passed arguments
    * NOT references.  This causes problems with cross-referencing necessary for the
    * observer design pattern.
    */
    function mgmediabot2( & $subject ) {
            parent::__construct( $subject );
            // load plugin parameters
            $this->_plugin = & JPluginHelper::getPlugin( 'content', 'mgmediabot2' );
            $this->_params = new JParameter( $this->_plugin->params );
    }

    /**
    * Plugin method with the same name as the event will be called automatically.
    */
    function onPrepareContent(&$row, &$params, &$limitstart) {
        global $mainframe, $mosConfig_absolute_path;
		// define the regular expression for the bot
		$regex = "#{mgmediabot2}(.*?){/mgmediabot2}#m";
		// check whether plugin has been unpublished
		// deletion of plugin lines is not supported anymore
		/*if ( !$this->_plugin->published ) {
			$row->text = preg_replace( $regex, '', $row->text );
		} else */ if (!is_file($mosConfig_absolute_path . "/components/com_mgmedia2/players.php")) {
			$row->text = "<b>mgmedia2 component not installed. Please install first to use the plugin.</b>";
		} else {
			// perform the replacement
			$row->text = preg_replace_callback( $regex, array( "mgmediabot2", 'mgmediabot2_replacer'), $row->text );
		}
		return true;
    }

	function mgmediabot2_replacer ( &$matches ) {
		global $mosConfig_absolute_path, $mosConfig_live_site, $mainframe, $database, $jscf;
		if (!defined("CALLED_INDIRECT")) {
			define("CALLED_INDIRECT", true);
		}
		#$mosConfig_absolute_path = $mainframe->getCfg( 'live_site' );
		#$mosConfig_live_site = $mainframe->getCfg( 'live_site' );
		#$database = $mainframe->getDBO();
		require_once($mosConfig_absolute_path . "/components/com_mgmedia2/players.php");
		$config = getMgmConfig();
		$matches[1] = cleanMgmLine($matches[1]);
		$oldparams = preg_replace("/=/", ",", $matches[1]);
		$params = parseMgmQs2($oldparams);
		if ( ((isset($params["popup"]) || isset($params["lightbox"]) ) && $params['width'] && $params['height']) || (!isset($params["popup"]) && is_array($params))) {
			if (isset($params["path"])) {
				$filename = basename($params['path'][0]);
				$extension = strtolower(preg_replace("#^.*\.(.*?)(\?.*){0,1}$#", "\\1", $filename));
			} else {
				if (isset($params["type"])) {
					$extension = $params["type"];
				} else {
					$extension = "none";
					return "If the parameter path is not given, at least type must be defined!";
				}
			}
			$params = parseMgmQs2($oldparams);
			if (!isset($params['type'])) {
				$oldparams = "type,$extension|" . $oldparams;
				$params = parseMgmQs2($oldparams);
			}
			$output = "";
			//only include ThickBox libs if thickbox is used
			if (isset($params['lightbox'])) {
				if (!defined("LIGHTBOX_INCLUDED")) {
					$mainframe->addCustomHeadTag ('<script type="text/javascript" src="' . $mosConfig_live_site . '/components/com_mgmedia2/thickbox/jquery.js"></script>');
					$mainframe->addCustomHeadTag ('<script type="text/javascript" src="' . $mosConfig_live_site . '/components/com_mgmedia2/thickbox/thickbox.js"></script>');
					$mainframe->addCustomHeadTag ('<link href="' . $mosConfig_live_site . '/components/com_mgmedia2/thickbox/thickbox.css" rel="stylesheet" type="text/css" media="screen" />');
					define("LIGHTBOX_INCLUDED", true);
				}
			}
			if (isset($params['lightbox'])) {$lightboxgrouping = $params['lightbox'];} else {$lightboxgrouping = "";}
			if (isset($params['lightboxpreview'])) {$lightboxpreview = $params['lightboxpreview'];} else {$lightboxpreview = "";}
			if (isset($params['lightboxcaption'])) {$lightboxcaption = $params['lightboxcaption'];} else {$lightboxcaption = $lightboxgrouping;}
			if (isset($params['popup'])) { $popupcaption = $params['popup']; } else { $popupcaption = "";}
			if (isset($params['popuppreview'])) {$popuppreview = $params['popuppreview'];} else {$popuppreview = "";}
			if (isset($params['popupcaption'])) {$popupcaption = $params['popupcaption'];}
			if ($lightboxpreview != "") {
				$lightboxlink = "<img src=\"$lightboxpreview\" border=\"0\" />";
			} elseif ($lightboxcaption != "") {
				$lightboxlink = $lightboxcaption;
			} else {
				$lightboxlink = $lightboxgrouping;
			}
			if ($popuppreview != "") {
				$popuplink = "<img src=\"$popuppreview\" border=\"0\" />";
			} else {
				$popuplink = $popupcaption;
			}
			$md5 = md5($oldparams);
			$query = "SELECT md5 FROM #__mgmediabot_playerscache WHERE md5 = '$md5'";
			$database->setQuery( $query );
			$result = $database->query();
			if ($database->getNumRows( $result ) < 1 ) {
				$query = "INSERT INTO #__mgmediabot_playerscache values('$md5', '$oldparams')";
			} else {
				$query = "REPLACE INTO #__mgmediabot_playerscache values('$md5', '$oldparams')";
			}
			$database->setQuery( $query );
			$result = $database->query();
			
			if (isset($params['popup'])) {
				$output .= "<a title=\"$popupcaption\" href=\"javascript: openPlayer('$mosConfig_live_site/index2.php?option=com_mgmedia2&mode=popup&playerid=$md5&no_html=1', ".$params['width'].", ".$params['height'].");\">$popuplink</a>";
			} elseif (isset($params['lightbox'])) {
				$output .= "<a title=\"$lightboxcaption\" rel=\"".preg_replace("#([^a-zA-Z0-9])#", "-", $lightboxgrouping)."\" href=\"$mosConfig_live_site/index2.php?option=com_mgmedia2&mode=lightbox&playerid=$md5&no_html=1&TB_iframe=true&width=".$params['width']."&height=".$params['height']."\" onclick=\"TB_show('$lightboxcaption', this.href, '".preg_replace("#([^a-zA-Z0-9])#", "-", $lightboxgrouping)."'); return false;\">$lightboxlink</a>";
			} else {
				$playercode = outputMgmPlayer2($params['type'], $params['path'][0],$params['width'],$params['height'], null, $md5, $oldparams, $params);
				if ($jscf){
					$output .= $playercode;
				} else {
					$output .= "<script language=\"Javascript\" type=\"text/javascript\" src=\"$mosConfig_live_site/index2.php?option=com_mgmedia2&mode=script&playerid=$md5&no_html=1\"></script>";
				}
			}
			if ($config['debug']){
				$output .= "<br />Parsed multiline: <br />".$matches[1]."<br />";
				$output .= "<br />mgmediabot params: $oldparams<br />";
				$output .= "<pre>" . print_r($params, true) ."</pre><br />\n";
			}
			return "<!-- http://www.needfude/mgmediabot-demo -->\n"."<!-- Start MgMedia2 -->\n" . $output . "\n<!-- End MgMedia2 -->\n";
		} else {
			return "Wrong count of parameters, please check the mgmediabot line";
		}
	}
}
$dispatcher = & JDispatcher::getInstance();
$dispatcher->attach(new mgmediabot2($dispatcher));
?>
